﻿Imports System.Linq
Partial Class App_FollowStat
    Inherits MyUI.PageBaseApp

    Public CurrAccount As mDB.Account

    'Public WithEvents GroupConsoleSearch As UI.GroupButton(Of LinkButton)
    Public WithEvents GroupConsoleDay As UI.GroupButton(Of LinkButton)

    'Protected SortGridQuery, SortGridFollStaus As UI.SortControl

#Region "PAGE"

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        CurrAccount = CurrUser.CurrAccount

        'GroupConsoleSearch = New UI.GroupButton(Of LinkButton)(Me.ViewState, "CONSOLE_SEARCH", "bottone-private-a")
        GroupConsoleDay = New UI.GroupButton(Of LinkButton)(Me.ViewState, "CONSOLE_DAY", "pg-count-h")

        If Not Me.IsPostBack Then
            SetDataPage()
        End If

    End Sub

    Private Sub SetDataPage()

        'SetListAccount()

        If CurrAccount IsNot Nothing Then
            SetDataConsole()
            'SetDataAccountFilter()
            SetDataAccountList()
        End If

    End Sub

#End Region

#Region "CONSOLE"

    Private Sub SetDataConsole()


        Dim AutoFollStatus = MyApp.EnumToDic(Of mDB.Auto_Follow_Account.StatusType)()
        UI.List.Bind(Me.DdlAutoFollStatus, AutoFollStatus, "value", "key", "", False)

        Dim query = CurrAccount.View_Query_AutoFollow.ToDataTable  'CurrAccount.Tab_Auto_Follow_Query.REL.Auto_Follow_Query.Query.SetSelect("query.id", "query.query").ToDataTable
        UI.List.Bind(Me.DdlAutoFollQuery, query, "query", "id", "", False)

        'Dim prof = CurrAccount.Tab_Auto_Follow_Profile.REL.Auto_Follow_Profile.PROFILE_Account.ToDataTable
        Dim prof = CurrAccount.Tab_Auto_Follow_Profile.REL.Auto_Follow_Profile.Account.ToDataTable
        UI.List.Bind(Me.DdlAutoFollProfile, prof, "username", "id", "", False)

        If Not Me.IsPostBack Then
            'Me.GroupConsoleSearch.SelectButton = Me.RbtSearchLink
            Me.GroupConsoleDay.SelectButton = Me.RbtDayAll
        End If



    End Sub
    'Private Sub SetDataAccountFilter()

    '    Dim f = CurrAccount.Tab_Account_Filter.ToDataTable
    '    UI.List.Bind(Me.DdlAccountFilter, f, "description", "id", "", False)
    '    Me.DdlAccountFilter.Items.Insert(0, New ListItem("-- Select  --", "0"))

    '    UI.List.Bind(Me.DdlOnLineList, CurrAccount.Tab_List.ToDataTable, "fullname", "id", "", False)



    'End Sub
    'Protected Sub BtnAddList_Click(sender As Object, e As EventArgs) Handles BtnAddList.Click

    '    Dim accs = CurrAccount.View_AccountLink_ByFilter(Me.GetDataFilter).
    '        SetSelect("account.account_code").
    '        Limit(1000).
    '    ToList(Of String)("account_code")

    '    Dim tw As New MyApp.Network.Twitter(CurrAccount.GetOauth)
    '    tw.AddList(New mDB.List With {.Fullname = Me.TxtNewList.Text}, accs)


    'End Sub

    'Protected Sub GroupConsoleSearch_onselected(value As String) Handles GroupConsoleSearch.Selected
    '    SetDataAccountList()
    'End Sub


#End Region

    '#Region "FILTER"

    '    Protected Sub BtnAddFilter_Click(sender As Object, e As EventArgs) Handles BtnAddFilter.Click

    '        Dim f = New mDB.Account_Filter With {
    '            .Account_Id = CurrAccount.Id, .Description = Me.TxtNewFilter.Text
    '        }

    '        f.Filter = Me.GetDataFilter

    '        DB.InsertOnSubmit(f)
    '        DB.SubmitChanges()

    '        'f.SaveFilter_Data()

    '        SetDataAccountFilter()

    '    End Sub
    '    Protected Sub BtnRemoveFilter_Click(sender As Object, e As EventArgs) Handles BtnRemoveFilter.Click

    '        CurrAccount.Tab_Account_Filter.ByPK(Me.DdlAccountFilter.SelectedValue).Delete.ExecuteCommand()

    '        SetDataAccountFilter()
    '    End Sub
    '    Protected Sub BtnSaveFilter_Click(sender As Object, e As EventArgs) Handles BtnSaveFilter.Click

    '        Dim f = CurrAccount.Tab_Account_Filter.GetByPK(Me.DdlAccountFilter.SelectedValue)

    '        f.Filter = Me.GetDataFilter
    '        DB.SubmitChanges()

    '        SetDataAccountFilter()

    '    End Sub
    '    Protected Sub DdlAccountFilter_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlAccountFilter.SelectedIndexChanged
    '        Dim f = CurrAccount.Tab_Account_Filter.GetByPK(Me.DdlAccountFilter.SelectedValue)

    '        If f Is Nothing Then
    '            f = New mDB.Account_Filter
    '        End If

    '        SetDataFilter(f.Filter)

    '    End Sub
    '    Private Sub SetDataFilter(f As mDB.Account.Filter)

    '        Me.TxtUsername.Text = f.Username
    '        Me.TxtFullname.Text = f.Fullname
    '        Me.TxtBeginDate.Text = MyUI.Print.DateInput(f.FromDate)
    '        Me.TxtEndDate.Text = MyUI.Print.DateInput(f.ToDate)
    '        UI.List.SetSelectValues(Me.DdlLinkType, f.IdsLink)
    '        UI.List.SetSelectValues(Me.DdlBusiness, f.IdsBusin)
    '        UI.List.SetSelectValues(Me.DdlStatus, f.IdsStatus)
    '        UI.List.SetSelectValues(Me.DdlCategories, f.IdsCat)
    '        UI.List.SetSelectValues(Me.DdlGender, f.IdsGend)
    '        UI.List.SetSelectValues(Me.DdlLanguageNot, f.IdsLangNot)
    '        UI.List.SetSelectValues(Me.DdlLanguage, f.IdsLang)

    '    End Sub
    '    Private Function GetDataFilter() As mDB.Account.Filter

    '        Return New mDB.Account.Filter With {
    '            .FromDate = Utils.Conv.ToDate(Me.TxtBeginDate.Text), .ToDate = Utils.Conv.ToDate(Me.TxtEndDate.Text),
    '            .Username = Me.TxtUsername.Text, .Fullname = Me.TxtFullname.Text,
    '            .IdsLink = UI.List.GetSelectValuesInt(Me.DdlLinkType),
    '            .IdsBusin = UI.List.GetSelectValuesInt(Me.DdlBusiness),
    '            .IdsStatus = UI.List.GetSelectValuesInt(Me.DdlStatus),
    '            .IdsCat = UI.List.GetSelectValuesInt(Me.DdlCategories),
    '            .IdsGend = UI.List.GetSelectValuesInt(Me.DdlGender),
    '            .IdsLangNot = UI.List.GetSelectValues(Me.DdlLanguageNot),
    '            .IdsLang = UI.List.GetSelectValues(Me.DdlLanguage)
    '        }
    '    End Function

    '#End Region

#Region "ACCOUNT LIST"

    Protected Sub SetDataAccountList()
        Dim List = Me.ListAutoFollowAccountStatus

        Me.PnlSearchAutoFollow.Visible = True
        Me.PnlAutoFollow.Visible = True
        Me.TxtFullname.Enabled = True
        Me.TxtFullname.Enabled = False

        'follcounter
        Me.LblFollCounter.Text = SF("follow {0}/{1}, unfollow {2}/{3}", CurrAccount.GetFriendCount(1), 50, CurrAccount.GetUnfollowCount(1), 100)


        '-------------------------------------------------------
        ' QUERY STATUS
        '-------------------------------------------------------
        Dim FromDate = Utils.Conv.ToDate(Me.TxtBeginDate.Text)
        Dim ToDate = Utils.Conv.ToDate(Me.TxtEndDate.Text)

        If FromDate = Date.MinValue Then
            FromDate = Now.AddDays(-30).Date
        End If
        If ToDate = Date.MinValue Then
            ToDate = Now.Date
        End If

        Dim StatusIds = UI.List.GetSelectValuesInt(Me.DdlAutoFollStatus) '(From i In Me.DdlAutoFollStatus.GetSelectedIndices Select CInt(Me.DdlAutoFollStatus.Items(i).Value)).ToList
        Dim QueryIds = UI.List.GetSelectValuesInt(Me.DdlAutoFollQuery) '(From i In Me.DdlAutoFollQuery.GetSelectedIndices Select CInt(Me.DdlAutoFollQuery.Items(i).Value)).ToList
        Dim ProfileIds = UI.List.GetSelectValuesInt(Me.DdlAutoFollProfile)

        Dim qStatus = CurrAccount.Tab_Auto_Follow_Account.REL.Auto_Follow_Account.Account
        If StatusIds.Count <> 0 Then
            qStatus.Where("status_id", "IN", StatusIds)
        End If
        If QueryIds.Count <> 0 Then
            qStatus.Where("source_id", "IN", QueryIds)
        End If
        If ProfileIds.Count <> 0 Then
            qStatus.Where("source_id", "IN", ProfileIds)
        End If
        If FromDate > Date.MinValue Then
            qStatus.Where("update_status_date", ">=", FromDate)
        End If
        If ToDate > Date.MinValue Then
            qStatus.Where("update_status_date", "<", ToDate.AddDays(1))
        End If
        If Me.TxtUsername.Text <> "" Then
            qStatus.Where("username", "like", SF("%{0}%", Me.TxtUsername.Text))
        End If
        If Utils.Conv.ToInt(Me.TxtNotFollowerFromDay.Text) <> 0 Then
            qStatus.Where("follow_date", "<", Now.AddDays(-Utils.Conv.ToInt(Me.TxtNotFollowerFromDay.Text)))
        End If


        Dim dtStatus = Me.DPAutoFollowAccountStatus.SortQuery(qStatus).Limit(1000).ToDataTable ' pp3.SortQuery(q).ToDataTable()

        '-------------------------------------------------------
        ' LAYOUT
        '-------------------------------------------------------

        'UI.Grid.Bind(Me.GridFollowStatus, dt)

        Dim DataBind As List(Of Object) = UI.ListData.Bind(List, dtStatus, {"account_to_foll_id"})

        MyUI.Data.SetListStatusAccount(CurrAccount, UI.ListData.GetRowsList(List), DataBind.Select(Function(o) o("account_code").ToString).ToList)

        'Dim g = Me.GridFollowStatus


        For Each gr In List.Items
            Dim dr = DataBind(UI.ListDataItem.GetIndexData(gr))
            Dim LblStatus = UI.ListDataItem.GetControl(Of Label)(gr, "LblStatus")

            Dim Status = DirectCast(dr("status_id"), mDB.Auto_Follow_Account.StatusType)

            Select Case Status
                Case mDB.Auto_Follow_Account.StatusType.PENDING, mDB.Auto_Follow_Account.StatusType.FOLLOW
                    LblStatus.ForeColor = Drawing.Color.Orange

                Case mDB.Auto_Follow_Account.StatusType.ALREADY_FRIEND, mDB.Auto_Follow_Account.StatusType.UNFOLLOW
                    LblStatus.ForeColor = Drawing.Color.Red

                Case mDB.Auto_Follow_Account.StatusType.ERROR
                    LblStatus.ForeColor = Drawing.Color.Gray

                Case Else
                    LblStatus.ForeColor = Drawing.Color.Green

            End Select


            LblStatus.Text = Status.ToString

        Next

        '-------------------------------------------------------
        ' QUERY SUMMARY
        '-------------------------------------------------------

        Dim qSummary = CurrAccount.Tab_Auto_Follow_Account
        If QueryIds.Count <> 0 Then
            qSummary.Where("source_id", "IN", QueryIds)
        End If
        If FromDate > Date.MinValue Then
            qSummary.Where("update_status_date", ">=", FromDate)
        End If
        If ToDate > Date.MinValue Then
            qSummary.Where("update_status_date", "<", ToDate.AddDays(1))
        End If

        Dim dtSummary = qSummary.
            Where("status_id", "IN", New List(Of Integer) From {mDB.Auto_Follow_Account.StatusType.BECOME_FOLLOWER, mDB.Auto_Follow_Account.StatusType.UNFOLLOW}).
            GroupBy("source_type_id", "source_id").
            Select(
                "source_type_id", "source_id", "source_description",
                "sum(if(status_id = " & mDB.Auto_Follow_Account.StatusType.BECOME_FOLLOWER & ",1,0)) as count_become_follower",
                "sum(if(status_id = " & mDB.Auto_Follow_Account.StatusType.UNFOLLOW & ",1,0)) as count_unfollower"
            ).
        ToDataTable()

        '-------------------------------------------------------
        ' DATI
        '-------------------------------------------------------

        Utils.DT.ComputeData.Compute(dtSummary, "tot", " ({'count_become_follower'} + {'count_unfollower'})")
        Utils.DT.ComputeData.Compute(dtSummary, "perc", "{'count_become_follower'} / {'tot'}  * 100 ")
        Utils.DT.ComputeData.Compute(dtSummary, "seg", " {'tot'} / {p0} * 100 ", "=sum(tot)")

        '-------------------------------------------------------
        ' LAYOUT
        '-------------------------------------------------------

        dtSummary.DefaultView.Sort = "perc desc"
        UI.ListData.Bind(Me.ListAutoFollowSummary, dtSummary)

        '-------------------------------------------------------
        ' GRAFICO CONVERSIONE
        '-------------------------------------------------------

        Dim dtchar = (From d In dtSummary Order By d("count_become_follower") Descending Take 10).ToList

        Dim DataChart = New List(Of Object())
        DataChart.Add({"query", "foll", "conv"})
        For ct = 0 To dtchar.Count - 1 ' dtSum.Rows.Count - 1
            DataChart.Add({
                dtchar(ct)("source_description"), (dtchar(ct)("count_become_follower")), dtchar(ct)("perc")
            })
        Next

        Dim json = MyApp.JSONSerialize(New With {
            .data = DataChart
        })

        Me.AddJScript(SF("DrawChartPostSend2({0});", json))

        '-------------------------------------------------------
        ' GRAFICO AUTOFOLL
        '-------------------------------------------------------

        Dim qStat = CurrAccount.Tab_Auto_Follow_Account
        If QueryIds.Count <> 0 Then
            qStat.Where("source_id", "IN", QueryIds)
        End If
        If ProfileIds.Count <> 0 Then
            qStat.Where("source_id", "IN", ProfileIds)
        End If

        If FromDate > Date.MinValue Then
            qStat.Where("follow_date", ">=", FromDate)
        End If
        If ToDate > Date.MinValue Then
            qStat.Where("follow_date", "<", ToDate.AddDays(1))
        End If

        Dim dtStat = qStat.GroupBy("date(follow_date)").
            Where("follow_date", ">", FromDate).
            SetSelect(
            "date(follow_date) as follow_date",
            "sum(if(status_id = " & mDB.Auto_Follow_Account.StatusType.BECOME_FOLLOWER & ",1,0)) as count_become_follower",
            "sum(if(status_id = " & mDB.Auto_Follow_Account.StatusType.UNFOLLOW & ",1,0)) as count_unfollow",
            "sum(1) as count_follower"
        ).ToDataTable

        DataChart = New List(Of Object())
        DataChart.Add({"data", "Follow", "Become follower", "Unfollower"})
        For ct = 0 To dtStat.Rows.Count - 1 'Step' Each d In qt1.ToList
            DataChart.Add({MyUI.Print.DateMonthDay(dtStat(ct)("follow_date").value), dtStat(ct)("count_follower"), dtStat(ct)("count_become_follower"), dtStat(ct)("count_unfollow")})
        Next

        json = MyApp.JSONSerialize(New With {
            .data = DataChart
        })

        Me.AddJScript(SF("DrawChartAutoFollow({0});", json))


        Me.UpPAutoFollow.Update()




    End Sub

    Protected Sub ListAutoFollowAccountStatus_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListAutoFollowAccountStatus.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id As Integer = UI.ListDataItem.GetKey(e.CommandSource)
            Dim fa = CurrAccount.Tab_Auto_Follow_Account(id).ToObj

            Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)

            Select Case e.CommandName

                Case "FOLLOW"

                    tw.FollowAccont(CurrAccount, fa.Account_To_Foll.Account_Code)
                    fa.Status_Id = mDB.Auto_Follow_Account.StatusType.FOLLOW
                    fa.Follow_Date = Now
                    fa.Update_Status_Date = Now
                    DB.SubmitChanges()

                    Me.SetDataAccountList()

                Case "UNFOLLOW"

                    tw.UnFollowAccont(CurrAccount, fa.Account_To_Foll.Account_Code)
                    fa.Status_Id = mDB.Auto_Follow_Account.StatusType.UNFOLLOW
                    fa.Unfollow_Date = Now
                    fa.Update_Status_Date = Now
                    DB.SubmitChanges()

                    Me.SetDataAccountList()

            End Select



        End If
    End Sub


    'Protected Function GetImageGenderType(b As mDB.Account.BusinessType, g As mDB.Gender_Name.Type) As String

    '    If b = GloukDB.Account.BusinessType.BUSINESS Then
    '        Return "business.png"
    '    Else
    '        If g = GloukDB.Gender_Name.Type.MALE Then
    '            Return "man.png"
    '        End If
    '        If g = GloukDB.Gender_Name.Type.FEMALE Then
    '            Return "woman.png"
    '        End If

    '    End If

    '    Return ""
    'End Function
    'Protected Function GetImageStatus(b As mDB.Account.StatusType) As String

    '    Select Case b
    '        Case GloukDB.Account.StatusType.FAKE
    '            Return "conn-fake.png"
    '        Case GloukDB.Account.StatusType.INACTIVE
    '            Return "conn-inactive.png"
    '        Case GloukDB.Account.StatusType.LOW_ACTIVITY, GloukDB.Account.StatusType.MEDIUM_ACTIVITY, GloukDB.Account.StatusType.HIGHT_ACTIVITY
    '            Return "conn-good.png"
    '        Case Else
    '            Return ""
    '    End Select

    'End Function

    'Protected Sub ChkExcluded_CheckedChanged(sender As Object, e As EventArgs)

    '    Dim chk As CheckBox = sender
    '    Dim row = UI.ListDataItem.GetRow(sender)
    '    Dim id = UI.ListDataItem.GetKey(row)

    '    'Dim link = CurrAccount.Tab_Account_Link(GloukDB.Account_Link.Type.FOLLOWER, id).ToObj
    '    Dim link = CurrAccount._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER, id).ToObj
    '    If link IsNot Nothing Then
    '        link.Excluded = chk.Checked

    '        DB.SubmitChanges()
    '    End If




    'End Sub

    Protected Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click

        SetDataAccountList()

    End Sub


#End Region


End Class







